﻿using Abp;
using Abp.Authorization;
using Abp.Collections.Extensions;
using Abp.Extensions;
using Abp.UI;
using Mt.Site.Core.Organizations.UserCache.Models;
using Mt.Site.Core.WorkFlows.Enum;
using Mt.Site.Core.WorkFlows.Permissions;
using Mt.Site.Core.WorkFlows.Process;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Mt.Site.Core.WorkFlows.Diy.Actions.Impl
{
    //转审
    public class BranchLineAction : ActionBase
    {
        private const string RequiredPermissionName = WorkFlowPermissions.Pages_Manage_WorkFlow_ZhuanShen;

        private readonly IPermissionChecker _permissionChecker;

        public BranchLineAction(IPermissionChecker permissionChecker)
        {
            _permissionChecker = permissionChecker;
        }

        public override string UniqueName => WorkFlowConst.OperationName.BranchLineActionName;
        public override bool NeedUserListArg => true;

        public override async Task<GetUserSelectionDataOutput> GetUserListAsync(IWorkFlowManager manager, Guid? nodeId, List<long> unitId)
        {
            //目前前台没有传入unitId的值，但还是直接使用0吧， 同时审核人员是否要做过滤呢？
            //需要新增默认选项
            var list = await manager.GetUserListAsync(null, null, null);

            var todoUsers = await manager.GetToDoUserListAsync();

            list.Users = list.Users.Where(c => !todoUsers.Contains(c.Id)).OrderByDescending(c => c.Order).ToList();
            list.ActionScheme = ActionScheme.Order;

            var schemelist = new List<NameValue>();
            foreach (ActionScheme item in System.Enum.GetValues(typeof(ActionScheme)))
            {
                var temp = new NameValue
                {
                    Name = EnumHelper.GetEnumDescription(item),
                    Value = item.RawValue().ToString()
                };
                schemelist.Add(temp);
            }
            list.ActionSchemeList = schemelist;
            return list;
        }

        public override async Task<bool> IsShowAsync(IWorkFlowManager manager)
        {
            var current = await manager.GetCurrentProcessAsync();
            if(current == null || current.OperationType == OperationType.PassRound)
            {
                return false;
            }

            var actionState = await manager.CheckActionStateAsync();
            //var isBranchLine = await manager.IsBranchLine();
            var canOperate = manager.CanOperate(UniqueName);
            if (actionState == ActionState.Todo && canOperate)
            {
                if (await _permissionChecker.IsGrantedAsync(RequiredPermissionName))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }

        public override async Task OperateAsync(IWorkFlowManager manager, object data)
        {
            var args = data as ActionArgs;
            if (args != null)
            {
                //提前验证，避免添加时过滤重复后分支无人办理
                args.UserIdList = await manager.RemoveToDoStateUserBeforeAddTaskAsync(args.UserIdList);
            }
            if (args == null || args.UserIdList.IsNullOrEmpty())
            {
                throw new UserFriendlyException("请选择人员及步骤");
            }
            if (args.UserIdList.Count == 1)
            {
                args.ActionScheme = ActionScheme.Single;
            }

            var isShow = await IsShowAsync(manager);
            if (isShow)
            {
                var current = await manager.GetCurrentProcessAsync();

                var names = await manager.UserAndUnitFinder.GetUserNameListAsync(args.UserIdList);
                var fromName = await manager.UserAndUnitFinder.GetUserNameAsync(current.UserId);
                var nextNameStr = string.Join("、", names);
                string msg = $"转{nextNameStr}审阅";

                await manager.HasSolved(args.ReplyMsg, msg, MoveMode.NewBranch);
                //写入新任务
                await manager.AddNewTaskInBranchAsync(current, args.UserIdList, args.ActionScheme, null);
                //写入记录
                var scheme = $"({EnumHelper.GetEnumDescription(args.ActionScheme)})";
                await manager.AddLogAsync(msg + scheme, fromName, nextNameStr, current?.Id);
            }
        }
    }
}